package org.kl.bf.web.basic;

import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.kl.bf.entity.basic.RunAsConfig;
import org.kl.bf.entity.basic.User;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.service.basic.RunAsConfigService;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 身份委托配置
 * 
 * @Author hqm
 * @CreateTime 2014年6月18日 下午2:23:29
 */
@Controller
@RequestMapping(value = "/basic/runAsConfig")
public class RunAsConfigController extends BasicController {
	@Autowired
	private RunAsConfigService runAsConfigService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/runAsConfigList";
	}

	/**
	 * 正在启用的授权
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	// @RequiresPermissions("runAsConfig:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "createTime") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_fromUser.id", BasicController.getCurrentUserId());
		searchParams.put("EQ_inUse", "1");
		Page<RunAsConfig> runAsConfigs = runAsConfigService.getRunAsConfig(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(runAsConfigs.getContent());
		grid.setTotal((int) runAsConfigs.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	/**
	 * 授权历史，包括有效和无效的
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "dataGrid_history", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGridHistory(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "inUse,createTime") String sortType,
			@RequestParam(value = "order", defaultValue = "desc,desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_fromUser.id", BasicController.getCurrentUserId());
		Page<RunAsConfig> runAsConfigs = runAsConfigService.getRunAsConfig(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(runAsConfigs.getContent());
		grid.setTotal((int) runAsConfigs.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	/**
	 * 被授权历史，有效无效的
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "dataGrid_granted", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGridGranted(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "inUse,createTime") String sortType,
			@RequestParam(value = "order", defaultValue = "desc,desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_toUser.id", BasicController.getCurrentUserId());
		Page<RunAsConfig> runAsConfigs = runAsConfigService.getRunAsConfig(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(runAsConfigs.getContent());
		grid.setTotal((int) runAsConfigs.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	// @RequiresPermissions("runAsConfig:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("runAsConfig") RunAsConfig runAsConfig,
			@RequestParam(value = "userId", defaultValue = "-1") String userId, RedirectAttributes redirectAttributes, HttpSession session) {
		try {
			runAsConfig.setToUser(new User(userId));
			runAsConfig.setFromUser(new User(BasicController.getCurrentUserId()));
			runAsConfigService.saveRunAsConfig(runAsConfig);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("编辑成功", true, null);
	}

	// @RequiresPermissions({ "runAsConfig:delete", "runAsConfig:update" })
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		runAsConfigService.revokeRunAsConfig(id);
		return ajaxMsg("取消成功", true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getRunAsConfig(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("runAsConfig", runAsConfigService.getRunAsConfig(id));
		}
	}
}
